/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.je.bpm.engine.impl.variable;

import com.je.bpm.engine.ActivitiException;
import com.je.bpm.engine.impl.context.Context;
import com.je.bpm.engine.impl.persistence.entity.VariableInstanceEntity;
import com.je.bpm.engine.impl.util.IoUtil;
import com.je.bpm.engine.impl.util.ReflectUtil;

import java.io.*;


public class SerializableType extends ByteArrayType {

    public static final String TYPE_NAME = "serializable";

    protected boolean trackDeserializedObjects;

    @Override
    public String getTypeName() {
        return TYPE_NAME;
    }

    public SerializableType() {

    }

    public SerializableType(boolean trackDeserializedObjects) {
        this.trackDeserializedObjects = trackDeserializedObjects;
    }

    @Override
    public Object getValue(ValueFields valueFields) {
        Object cachedObject = valueFields.getCachedValue();
        if (cachedObject != null) {
            return cachedObject;
        }
        byte[] bytes = (byte[]) super.getValue(valueFields);
        if (bytes != null) {
            Object deserializedObject = deserialize(bytes, valueFields);
            valueFields.setCachedValue(deserializedObject);
            if (trackDeserializedObjects && valueFields instanceof VariableInstanceEntity) {
                Context.getCommandContext().addCloseListener(new VerifyDeserializedObjectCommandContextCloseListener(
                        new DeserializedObject(this, valueFields.getCachedValue(), bytes, (VariableInstanceEntity) valueFields)));
            }
            return deserializedObject;
        }
        return null; // byte array is null
    }

    @Override
    public void setValue(Object value, ValueFields valueFields) {
        byte[] bytes = serialize(value, valueFields);
        valueFields.setCachedValue(value);
        super.setValue(bytes, valueFields);

        if (trackDeserializedObjects && valueFields instanceof VariableInstanceEntity) {
            Context.getCommandContext().addCloseListener(new VerifyDeserializedObjectCommandContextCloseListener(
                    new DeserializedObject(this, valueFields.getCachedValue(), bytes, (VariableInstanceEntity) valueFields)));
        }

    }

    public byte[] serialize(Object value, ValueFields valueFields) {
        if (value == null) {
            return null;
        }
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ObjectOutputStream oos = null;
        try {
            oos = createObjectOutputStream(baos);
            oos.writeObject(value);
        } catch (Exception e) {
            throw new ActivitiException("Couldn't serialize value '" + value + "' in variable '" + valueFields.getName() + "'", e);
        } finally {
            IoUtil.closeSilently(oos);
        }
        return baos.toByteArray();
    }

    public Object deserialize(byte[] bytes, ValueFields valueFields) {
        ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
        try {
            ObjectInputStream ois = createObjectInputStream(bais);
            Object deserializedObject = ois.readObject();

            return deserializedObject;
        } catch (Exception e) {
            throw new ActivitiException("Couldn't deserialize object in variable '" + valueFields.getName() + "'", e);
        } finally {
            IoUtil.closeSilently(bais);
        }
    }

    @Override
    public boolean isAbleToStore(Object value) {
        // TODO don't we need null support here?
        return value instanceof Serializable;
    }

    protected ObjectInputStream createObjectInputStream(InputStream is) throws IOException {
        return new ObjectInputStream(is) {
            @Override
            protected Class<?> resolveClass(ObjectStreamClass desc) throws IOException, ClassNotFoundException {
                return ReflectUtil.loadClass(desc.getName());
            }
        };
    }

    protected ObjectOutputStream createObjectOutputStream(OutputStream os) throws IOException {
        return new ObjectOutputStream(os);
    }
}
